package com.pansoft.openplanet.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.chat.view.CommonOtherPopWindow;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.TotalAssetsAddActivity;
import com.pansoft.openplanet.adapter.TotalAssetsAdapter;
import com.pansoft.openplanet.bean.TotalAssetBean;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.manager.MarketExchangeSiteManager.getCurrentMarketSite;

/**
 * 总资产界面
 *
 * @author will
 */
public class TotalAssetsFragment extends BaseFragment {

    private static final String TAG = "TotalAssetsFragment";
    private RecyclerView recyclerView;
    protected SmartRefreshLayout refreshLayout;
    private TotalAssetsAdapter adapter;
    private List<TotalAssetBean> assetBeans = new ArrayList<>();
    public static final int ADD_ASSET_CODE = 1563;
    /**
     * 是否显示数据信息的状态
     */
    private boolean isShowNumFlag = Boolean.parseBoolean(EnvironmentVariable.getProperty("asset_show_num", "true"));

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.open_planet_fragment_total_assets, container, false);
        initView(view);

        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new TotalAssetsAdapter(getActivity(), assetBeans);
        recyclerView.setAdapter(adapter);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {


            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
        //适配器眼睛按钮的点击事件
        adapter.setOnEyeShowNumClickListener(new TotalAssetsAdapter.OnEyeShowNumClickListener() {
            @Override
            public void isShowNmu() {
                //保存是否显示数据信息的状态
                saveShowNumStatus(isShowNumFlag = !isShowNumFlag);
                //
                for (TotalAssetBean assetBean : assetBeans) {
                    assetBean.setShowNum(isShowNumFlag);
                }
                adapter.notifyDataSetChanged();
            }
        });
        refreshLayout.autoRefresh();
    }

    /**
     * 保存是否显示数据信息的状态
     */
    private void saveShowNumStatus(boolean isShowNum) {
        EnvironmentVariable.setProperty("asset_show_num", String.valueOf(isShowNum));
    }

    private void initData() {
        assetBeans.clear();
        //头部
        assetBeans.add(new TotalAssetBean.Builder().rmbValue("0.00").isShowNum(isShowNumFlag).build());
        adapter.notifyDataSetChanged();
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getUserName());
        //allAccountFollowTrusteeshipCoinList 以前的接口
        //allAccountFollowCoinListExceptBalance 现在的接口为解决接口加载慢的情况 先只请求币的列表，再请求币的余额 数量信息allAccountFollowCoinList()
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/allAccountFollowCoinListExceptBalance", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        refreshLayout.finishRefresh(100);
                        try {
                            //http://tc.solarsource.cn:9692//tcserver/trusteeship/allAccountFollowTrusteeshipCoinList?userId=18653187079
                            JSONObject jsonObject = new JSONObject(response);
                            disposeRequestData(0, jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        refreshLayout.finishRefresh(100);
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 请求代币余额数量信息
     */
    private void allAccountFollowCoinList() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getUserName());
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/allAccountFollowCoinList", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            disposeRequestData(1, jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
    }

    /**
     * 处理请求的JSon数据
     *
     * @param status     0 是处理allAccountFollowCoinListExceptBalance接口请求的数据，没有余额和代币的数量
     *                   1 是处理allAccountFollowCoinList  更新余额和数量
     * @param jsonObject 处理的数据
     */
    private void disposeRequestData(int status, JSONObject jsonObject) {
        JSONArray list = jsonObject.optJSONArray("userFollowTrusteeshipCoin");
        if (jsonObject.optString("result").equals("success")) {
            if (list.length() > 0) {
                for (int i = 0; i < list.length(); i++) {
                    JSONObject object = list.optJSONObject(i);
                    //代币数量
//                                        String coin = TCMathUtil.retainAsignDecimals(object.optDouble("availableCoin"), 5);
                    String coin = BalanceUtil.formatPrice(object.optDouble("availableCoin"), true, 5);
                    //代笔单价
                    double rate = object.optDouble("coinMarketPrice");
                    String currentRate = BalanceUtil.formatPrice(MarketNumberUtils.
                            getRealPrice(getCurrentMarketSite(),
                                    "CNY",
                                    CurrencyAndBourseManager.getCurrencyUnitCode(),
                                    rate), true, 2);
                    //当前代币总价值
                    double rmbValue = object.optDouble("userCoinMarketNum");
                    double currentValue = MarketNumberUtils
                            .getRealPrice(getCurrentMarketSite(),
                                    "CNY",
                                    CurrencyAndBourseManager.getCurrencyUnitCode(),
                                    rmbValue);
                    String rmb = BalanceUtil.formatPrice(currentValue, true, 2);
                    if (status == 0) {
                        TotalAssetBean assetBean = new TotalAssetBean.Builder()
                                .assetName(object.optString("coinName"))
                                .assetValue(coin)
                                .rmbValue(rmb + " " + CurrencyAndBourseManager.getCurrencyUnitCode())
                                .rate("≈" + currentRate + " " + CurrencyAndBourseManager.getCurrencyUnitCode())
                                .assetIcon(object.optString("coinIcon"))
                                .isShowNum(isShowNumFlag).build();
                        assetBeans.add(assetBean);
                        //请求代币余额 数量等信息数据
                        assetBeans.get(0).setRmbValue("0.00");

                    } else if (status == 1) {
                        if (assetBeans != null && assetBeans.size() > 0) {
                            for (TotalAssetBean assetBean : assetBeans) {
                                if (assetBean.getAssetName() != null && assetBean.getAssetName().equals(object.optString("coinName"))) {
                                    assetBean.setRmbValue(rmb + " " + CurrencyAndBourseManager.getCurrencyUnitCode());
                                    assetBean.setAssetValue(coin);
                                    assetBean.setRate("≈" + currentRate + " " + CurrencyAndBourseManager.getCurrencyUnitCode());
                                }
                            }
                            //更新头部所有的总的人民币值
                            double totalPrice = MarketNumberUtils
                                    .getRealPrice(getCurrentMarketSite(),
                                            "CNY",
                                            CurrencyAndBourseManager.getCurrencyUnitCode(),
                                            jsonObject.optDouble("num"));
                            String currentTotalPrice = BalanceUtil.formatPrice(totalPrice, true, 2);
                            assetBeans.get(0).setRmbValue(currentTotalPrice);
                        }

                    }
                }
                //只有请求列表后才请求代币余额数量信息
                if (status == 0) {
                    //请求代币余额 数量等信息数据
                    allAccountFollowCoinList();
//                    if(assetBeans!=null&&assetBeans.size()>0){
//                        for(TotalAssetBean totalAssetBean : assetBeans){
//                            totalAssetBean.setRmbValue("--");
//                            totalAssetBean.setRate("--");
//                            totalAssetBean.setAssetValue("--");
//
//                        }
//                    }
                }
            }
            adapter.notifyDataSetChanged();
        } else {
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        EFHttpRequest.cancelRequest(TAG);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showPopMenu1(RightTopMenuClickEvent event) {
        StubObject stubObject = event.getStubObject();
//        if (stubObject.getString("AndroidShow", "").equals("com.pansoft.openplanet.fragment.TotalAssetsFragment")) {
//            //先弹出popupWindow
//            showPopup(getActivity(), event.getView());
//        }
    }

    public void showPopup(final Context context, View imageView) {
        final CommonOtherPopWindow commonOtherPopWindow = new CommonOtherPopWindow((Activity) context);
        commonOtherPopWindow.addMenuButton("选择资产", R.drawable.open_plant_import_fans)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //创建钱包
                        commonOtherPopWindow.dismiss();
                        Intent intent = new Intent(context, TotalAssetsAddActivity.class);
                        startActivityForResult(intent, ADD_ASSET_CODE);
                    }
                });
        commonOtherPopWindow.showPopupWindow(imageView);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_ASSET_CODE && resultCode == RESULT_OK) {
            refreshLayout.autoRefresh();
        }
    }
}
